<template>
    <el-form label-width="110px" size="small">
        <el-row class="form-row">
            <el-col :span="12">
                <el-form-item label="产品代码:">
                    <RiskEntryInput id="fundCode" @set-entry-data="getEntryslist" :returnDatas="instructionCache.fundCode" />
                </el-form-item>
                <el-form-item label="资产单元编号:" v-show="SHOW_SECURITY">
                    <el-select v-model="instructionCache.assetCode" size="mini">
                        <el-option
                            v-for="i in computedAssetCodeSelectData"
                            :key="i.assetCode"
                            :label="i.assetCode + ' ' + i.assetName"
                            :value="i.assetCode"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="组合编码:">
                    <el-select name="组合编码" v-model="instructionCache.fundAccountCode" size="mini" @change="handleFundAccountCodeChange">
                        <el-option
                            v-for="i in computedFundAccountCodeSelectData"
                            :key="i.fundAccountCode"
                            :label="i.fundAccountCode + ' ' + i.fundAccountName"
                            :value="i.fundAccountCode"
                            :name="'fundAccountCode-' + i.fundAccountCode"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="业务类型:">
                    <el-select name="businessType" disabled size="mini" v-model="instructionCache.businessType">
                        <el-option label="B 存款类" value="B"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="委托方向:">
                    <el-select
                        name="orderDirection"
                        v-model="instructionCache.orderDirection"
                        size="mini"
                        :class="['font-color-' + textColor]"
                        @change="handleChange('orderDirection')"
                    >
                        <el-option label="存款" value="F"> </el-option>
                        <el-option label="存款支取" value="i"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="目标类型:">
                    <el-select name="targetType" v-model="instructionCache.targetType" size="mini" disabled>
                        <el-option v-for="(value, key) in targetTypePojo" :key="key" :label="value" :value="key"> </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="存单号:">
                    <el-select name="receiptNo" v-model="instructionCache.receiptNo" size="mini" @change="handleSelect">
                        <el-option
                            v-for="i in receiptNoData"
                            :key="i.receiptNo"
                            :label="i.receiptNo"
                            :value="i.receiptNo"
                            :style="{ color: i.isGivenOrder == '1' ? '#ccc' : '' }"
                            :name="'receiptNo' + i.receiptNo"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="支取类型:">
                    <el-select name="advanceType" size="mini" v-model="instructionCache.advanceType" @change="handleChange('advanceType')">
                        <el-option
                            v-for="i in withDrawSelectData"
                            :key="i.dictKey"
                            :label="i.dictKeyName"
                            :value="i.dictKey"
                            :name="'advanceType-' + i.dictKey"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="支取日期:"
                    ><el-date-picker
                        name="drawDate"
                        v-model="instructionCache.drawDate"
                        type="date"
                        format="yyyy/MM/dd"
                        value-format="yyyyMMdd"
                        placeholder="请选择"
                        style="width: 100%"
                        :picker-options="pickerOptions"
                        @change="handleChange('drawDate')"
                    ></el-date-picker
                ></el-form-item>
                <el-form-item label="利息金额:">
                    <RiskInputNumber
                        name="drawInterest"
                        :maxlength="15"
                        :input="instructionCache.drawInterest"
                        :inputAfter="'元'"
                        :colorStyle="textColor"
                        :precision="2"
                        :field="'drawInterest'"
                        @getInputNumber="getInputNumber(arguments)"
                    >
                    </RiskInputNumber>
                </el-form-item>
                <el-form-item label="兑付金额:">
                    <RiskInputNumber
                        name="orderBalance"
                        :maxlength="15"
                        :input="instructionCache.orderBalance"
                        :inputAfter="'元'"
                        :colorStyle="textColor"
                        :precision="2"
                        :field="'orderBalance'"
                        :disabled="true"
                        @getInputNumber="getInputNumber(arguments)"
                    >
                    </RiskInputNumber>
                </el-form-item>
            </el-col>
        </el-row>
    </el-form>
</template>
<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import DictionConstUtil, { SGU_CACHE } from '@/utils/diction-const-util';
import moment from 'moment';
import RiskEntryInput from '@/common/components/risk-entry-input.vue';
import RiskInputNumber from '@/pages/risk-measure/components/risk-input-number.vue';
import { getConfigItem, uniqueFunc } from '@/utils/tools';

// 存款支取指令风险下单Tab
export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}
@Component({
    name: 'CkPaid',
    components: {
        RiskEntryInput,
        RiskInputNumber,
    },
})
export default class CkPaid extends Vue {
    @Prop()
    paidDetail: any;
    @Prop()
    renderCount: number;
    @Prop()
    stockInfoCache: any;

    instructionCache: any = {
        fundCode: '',
        receiptNo: '', // 存单号
        fundAccountCode: '',
        fundAccountName: '',
        assetCode: '',
        assetName: '',
        drawInterest: '', // 利息金额
        advanceType: '1', // 支取类型
        orderBalance: '', // 兑付金额
        businessType: 'B',
        drawDate: '', // 支取日期
        orderDirection: 'i', // 委托方向
        targetType: '2',
    };

    withDrawSelectData: any[] = [
        { dictKeyName: '提前兑付', dictKey: '1' },
        { dictKeyName: '通知兑付', dictKey: '2' },
        { dictKeyName: '解约', dictKey: '3' },
        { dictKeyName: '到期兑付', dictKey: '4' },
    ]; // 支取类型下拉数据

    pickerOptions: any = {};

    stockInfo: any = {}; // 证券信息

    fundAccountCodeSelectData: any[] = [];

    fundCodeSelectData: any[] = []; // 产品序号下拉框数据

    receiptNoData: any[] = []; // 存单号数据

    currentTradeDay: number = 0;

    textColor: string = 'green';

    stockReport: any[] = []; // 证券代码下拉框数据
    targetTypePojo: any = {}; // 目标类型

    // // 监听 组合编码计算属性 (每当计算属性变动时 自动选中第一项)
    // @Watch('computedFundAccountCodeSelectData', { immediate: true, deep: true })
    // watchcomputedFundAccountCode(newData) {
    //     if (this.paidDetail) {
    //         this.instructionCache.fundAccountCode = this.paidDetail.fundAccountCode;
    //     } else {
    //         if (newData && newData.length) {
    //             this.instructionCache.fundAccountCode = newData[0].fundAccountCode;
    //         }
    //     }
    // }
    SHOW_SECURITY = getConfigItem('SHOW_SECURITY');
    // 监听 资产单元计算属性 (每当计算属性变动时 自动选中第一项)
    @Watch('computedAssetCodeSelectData', { immediate: true, deep: true })
    watchcomputedAssetCode(newData) {
        if (!this.SHOW_SECURITY) {
            return;
        }
        let obj: any = {};
        if (newData && newData.length) {
            const d1 = newData.find(item => item.assetCode == this.instructionCache.assetCode);
            obj = d1 || newData[0];
        }
        this.instructionCache.assetCode = obj.assetCode;
        this.instructionCache.assetName = obj.assetName;
    }

    // 监听 组合编码计算属性 (每当计算属性变动时 自动选中第一项)
    @Watch('computedFundAccountCodeSelectData', { immediate: true, deep: true })
    watchcomputedFundAccountCode(newData) {
        let obj: any = {};
        if (newData && newData.length) {
            const d1 = newData.find(item => item['fundAccountCode'] == this.instructionCache['fundAccountCode']);
            obj = d1 || newData[0];
        }
        this.instructionCache.assetCode = obj.assetCode;
        this.instructionCache.assetName = obj.assetName;
        this.instructionCache.fundAccountCode = obj.fundAccountCode;
        this.instructionCache.fundAccountName = obj.fundAccountName;
    }

    get computedAssetCodeSelectData(): any {
        return uniqueFunc(this.fundAccountCodeSelectData[this.instructionCache.fundCode], 'assetCode');
    }

    // 组合编码下拉框计算属性;
    get computedFundAccountCodeSelectData() {
        let data = this.fundAccountCodeSelectData[this.instructionCache.fundCode];
        let retData = [];
        if (data && this.SHOW_SECURITY) {
            const obj = data.filter(item => item.assetCode == this.instructionCache.assetCode);
            retData = obj || [];
        } else {
            retData = data;
        }
        return retData;
    }

    // @Watch('paidDetail', { immediate: true, deep: true })
    @Watch('renderCount', { immediate: true, deep: true })
    async onWatchPaidDetail(newValue, oldValue) {
        console.log(this.paidDetail, this.instructionCache);

        if (JSON.stringify(this.paidDetail) !== JSON.stringify(this.instructionCache)) {
            if (this.paidDetail && this.paidDetail.orderDirection == 'i') {
                await this.getCurrentTradeDay();

                // 获取组合编码下拉框数据
                let arr = await SGU_CACHE('FundAccount', '/fundInfo/accounts', []);
                arr.forEach(item => {
                    this.fundAccountCodeSelectData[item.fundCode] = item.fundAccounts;
                });

                let instruction = this.paidDetail;

                this.prohFundCode = true;

                for (const key in instruction) {
                    if (key == 'drawDate') {
                        this.instructionCache.drawDate = this.paidDetail.drawDate || this.instructionCache.drawDate;
                    } else {
                        this.instructionCache[key] = this.paidDetail[key];
                    }
                }
                this.instructionCache.targetType = '2';

                await this.getFundPositionList();

                this.instructionCache.advanceType = this.paidDetail.advanceType || '1';
                this.instructionCache.businessType = 'B';

                await this.getstockCodeList(instruction.reportCode);
                this.stockInfo = this.stockReport.find(
                    item => item.reportCode === { '1': '870870', '2': '860860', '3': '890890', '6': '880880' }[this.paidDetail.depositType]
                );
                this.$emit('getStockInfo', this.stockInfo, '5');
            }
        } else {
            console.log('重置');
            this.instructionCache = {
                fundCode: '',
                receiptNo: '', // 存单号
                fundAccountCode: '',
                fundAccountName: '',
                assetCode: '',
                assetName: '',
                drawInterest: '', // 利息金额
                advanceType: '1', // 支取类型
                orderBalance: '', // 兑付金额
                businessType: 'B',
                drawDate: '', // 支取日期
                orderDirection: 'i', // 委托方向
            };
        }
        console.log(this.instructionCache);
        console.log(this.targetTypePojo, 'targetTypePojo');
    }

    @Watch('stockInfoCache', { immediate: true, deep: true })
    onWatchStockInfo() {
        if (this.stockInfoCache) {
            this.stockInfo = this.stockInfoCache;
            // this.orderDirectionSelectData = this.stockInfoCache.tradeDirections;
            // this.getStockCodeList(this.stockInfo.reportCode);
        }
    }

    async created() {
        // 获取目标类型
        this.targetTypePojo = DictionConstUtil.targetType;
        // 获取产品信息 (产品序号下拉框数据)
        this.fundCodeSelectData = await SGU_CACHE('FundInfo', '/fundInfo/list', []);

        // 获取组合编码下拉框数据
        let arr = await SGU_CACHE('FundAccount', '/fundInfo/accounts', []);
        arr.forEach(item => {
            this.fundAccountCodeSelectData[item.fundCode] = item.fundAccounts;
        });
    }

    // 产品代码回调
    getEntryslist(val: any) {
        if (this.instructionCache.fundCode != val) {
            this.prohFundCode = false;
            this.instructionCache.fundCode = val;
            this.handleFundCodeChange(val);
        }
    }

    handleChange(param) {
        if (param == 'orderDirection') {
            this.instructionCache = {
                fundCode: this.instructionCache.fundCode,
                fundNameSt: this.instructionCache.fundNameSt,
                fundAccountCode: this.instructionCache.fundAccountCode,
                fundAccountName: this.instructionCache.fundAccountName,
                assetCode: this.instructionCache.assetCode,
                assetName: this.instructionCache.assetName,
                orderDirection: 'F',
            };
        }
        this.instructionCache.instructionTypeName = '存款类';
        this.$emit('handleSettingValue', this.instructionCache, '5');
    }

    prohFundCode: boolean = false;

    async handleFundCodeChange(val: string) {
        // !val ||

        let fund = this.fundCodeSelectData.find(item => item.fundCode === val) || {};
        this.instructionCache.fundNameSt = fund.fundNameSt;

        let fundAccount = (this.fundAccountCodeSelectData[this.instructionCache.fundCode] || [])[0] || {};
        this.instructionCache.fundAccountCode = fundAccount.fundAccountCode;
        this.instructionCache.fundAccountName = fundAccount.fundAccountName;
        this.instructionCache.assetCode = fundAccount.assetCode;
        this.instructionCache.assetName = fundAccount.assetName;

        if (this.prohFundCode) {
            this.prohFundCode = false;
            return;
        }

        await this.getFundPositionList();
        console.log('33333333333', this.prohFundCode);
        this.prohFundCode = false;
        // debugger;
        // this.instructionCache.receiptNo = '';
        await this.handleSelect(this.instructionCache.receiptNo);
    }

    // 获取证券代码下拉框数据
    async getstockCodeList(value: string) {
        await this.$axios
            .post('/dict/stock/report/select/' + 6, {
                dictKey: value,
                dictKeyName: value,
            })
            .then((res: any) => {
                this.stockReport = res || [];
            });
    }

    // 组合编码变化
    handleFundAccountCodeChange(value: string): void {
        let fundAccount = (this.fundAccountCodeSelectData[this.instructionCache.fundCode] || []).find(item => item.fundAccountCode === value) || {};

        this.instructionCache.fundAccountName = fundAccount.fundAccountName;
        this.instructionCache.assetCode = fundAccount.assetCode;
        this.instructionCache.assetName = fundAccount.assetName;
        this.handleChange('fundAccountCode');
    }

    // 选中可支取存单事件
    async handleSelect(receiptNo: any) {
        let disabled: boolean = false;

        for (let index = 0; index < this.receiptNoData.length; index++) {
            if (this.receiptNoData[index].receiptNo == receiptNo && this.receiptNoData[index].isGivenOrder) {
                this.yh_message_warn('当日已支取过，不可重复支取！');
                this.instructionCache.receiptNo = '';
                disabled = true;
                break;
            }
        }
        if (disabled) {
            return;
        }

        let row = this.receiptNoData.find(item => item.receiptNo == receiptNo) || {};

        this.instructionCache.reportCode = row.reportCode;

        // this.instructionCache.receiptNo = row.receiptNo; // 存单号

        this.instructionCache.depositRate = row.rate;
        // this.instructionCache.depositStartDate = row.beginDate;
        this.instructionCache.mutureDate = row.endDate;
        // this.instructionCache.drawInterest = row.receivableInterest;
        this.instructionCache.orderBalance = row.balance;
        this.instructionCache.expireBalance = Number(row.receivableInterest) + Number(row.balance);
        this.instructionCache.bankCode = row.bankNo;
        this.instructionCache.advanceLimitFlag = row.advanceLimitFlag;

        this.instructionCache.receivableInterest = row.receivableInterest; //
        this.instructionCache.balance = row.balance;
        this.instructionCache.confirmNo = row.confirmNo;
        this.instructionCache.depositType = row.depositType;

        this.instructionCache.drawInterest = row.receivableInterest;
        this.instructionCache.depositStartDate = row.beginDate;

        this.stockInfo = this.stockReport.find(
            item => item.reportCode === { '1': '870870', '2': '860860', '3': '890890', '6': '880880' }[row.depositType]
        );
        this.$emit('getStockInfo', this.stockInfo, '5');

        this.handleChange('receiptNo');
    }

    // 获取当前交易日期
    getCurrentTradeDay() {
        return new Promise((resolve, reject) => {
            this.$axios
                .get('/dict/initTradeDate')
                .then((res: any) => {
                    this.currentTradeDay = res;
                    this.instructionCache.drawDate = this.currentTradeDay.toString();
                    let date = new Date(moment(this.currentTradeDay.toString()).format('YYYY-MM-DD')).getTime();
                    this.pickerOptions = {
                        disabledDate(time) {
                            return time.getTime() < date - 1 * 24 * 3600 * 1000;
                        },
                    };
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
    }

    // 利息金额、兑付金额
    getInputNumber(args: any) {
        let value = args[0];
        let field = args[1];
        this.instructionCache[field] = value;
        this.handleChange(args[1]);
    }

    // 可支取存单信息分页
    getFundPositionList() {
        return new Promise((resolve, reject) => {
            this.$axios
                .post('/position/bankDeposit/operationalReceipt/select', { fundCode: [this.instructionCache.fundCode] })
                .then((res: any) => {
                    res.forEach(ele => {
                        ele.totalBalance = Number(ele.balance || '0') + Number(ele.receivableInterest || '0');
                    });
                    this.receiptNoData = res;
                    if (res.length < 1) {
                        this.instructionCache.receiptNo = '';
                    }
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
    }
}
</script>
<style lang="scss" scoped>
@import '@/pages/risk-measure/style/measure';
.font-color-green {
    /deep/ input {
        color: green !important;
    }
    /deep/ .el-input-group__append {
        color: green !important;
    }
}
</style>
